package com.ych.DemoSSM.usercenter.web.controller;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

public class UserLoginFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpSession session = request.getSession();
        Map<String, Object> userInfo = (Map<String, Object>) session.getAttribute("userInfo");
        if (userInfo == null) {
            arg1.setContentType("application/json;charset=utf-8");
            OutputStream os = arg1.getOutputStream();
            os.write("{\"code\":\"1001\",\"message\":\"用户未登录\"}".getBytes("UTF-8"));
            os.flush();
            os.close();
            return;
        }
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}
